from django.shortcuts import render
from .models import *
from .serializer import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from werkzeug.security import generate_password_hash,check_password_hash
from utlis.utils_token import login_token
from django.http import HttpResponse
from captcha.image import ImageCaptcha
from rest_framework.viewsets import ModelViewSet
import json,redis,random,string,datetime
from django.db.models import Q
from utlis.ip_address.ip_info import CzIp
from .tasks import send_sms
from utlis.user_login import check_login
# Create your views here.


# 获取图片验证码
class ImgCode(APIView):
    redis_conn = redis.Redis(host='localhost', password='123', db=2, port=6379)
    def get(self,request,uuid):
        try:
            salt = "".join(random.sample(string.ascii_letters+string.digits, 4))
            img = ImageCaptcha()
            image = img.generate(salt)
            self.redis_conn.set(f"img_{uuid}", salt, ex=60 * 5)
            code = self.redis_conn.get(f"img_{uuid}")
            code = code.decode()
            print('验证码：', code)
            return HttpResponse(image,content_type='image/png')
        except Exception as e:
            print("错误>>>>>", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, 'message': f"服务器错误{e}"})


# 发送验证码
class SmsAPIView(APIView):
    def post(self, request):
        try:
            # 获取前端数据
            mobile = request.data.get('mobile')
            print("获取到的手机号>>>", mobile)
            # 数据校验
            if not all([mobile,]):
                return Response({
                    "code": 400,
                    "msg": "数据不完整"
                })
            # 生成验证码
            sms_code = "%d"%random.randint(10000,99999)

            print('验证码:', sms_code)
            # 存入redis
            redis_coon = redis.Redis(host='localhost', port=6379, password='123', db=3)
            redis_coon.set("sms_%s"%mobile,sms_code,ex=300)
            # rds = redis_coon.get("sms_%s"%mobile)
            # print('red', rds)

            # 请求容联云发送短信验证码
            res = send_sms.delay(sms_code,mobile)

            return Response({
                'code':200,
                'msg':'短信验证码发送成功！',
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 用户登录
class UserLogin(APIView):
    cz = CzIp()
    redis_conn = redis.Redis(host='localhost', password='123', db=2, port=6379)
    def post(self, request):
        try:
            username = request.data.get("username")
            password = request.data.get("password")
            img_code = request.data.get("img_code")
            uuid = request.data.get("uuid")
            print('img_code', img_code)
            print('addc', username)
            print('uuid__', uuid)

            user = UserModel.objects.filter(username=username, is_delete=False).first()
            if not user:
               return Response({
                   "code": status.HTTP_204_NO_CONTENT,
                   "message": "没有该账号！"
               })

            code = self.redis_conn.get(f"img_{uuid}")
            if code == None:
                return Response({"code": status.HTTP_400_BAD_REQUEST, "message": "验证码已过期！"})
            code = code.decode()
            print('code>>>>>', code.lower())
            if img_code.lower() != code.lower():
                return Response({"code": status.HTTP_400_BAD_REQUEST, "message": "验证码错误！"})
            if check_password_hash(user.password,password):
            # pwd = UserModel.objects.filter(password=password, is_delete=False).first()
            # if pwd:
                payload = {
                    'id': user.id,
                    'name': user.username
                }
                token,refresh_token = login_token(payload)
                path = request.path_info
                method = request.method.lower()
                x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')  # 判断是否使用代理
                if x_forwarded_for:
                    ip = x_forwarded_for.split(',')[0]  # 使用代理获取真实的ip
                else:
                    ip = request.META.get('REMOTE_ADDR')  # 未使用代理获取IP
                address = self.cz.get_addr_by_ip(ip)
                facility = request.headers.get("User-Agent")
                Operate_LogModel.objects.create(name="登录", staff_id=user.id, path=f"{method} {path}", ip=ip, address=address,
                                                facility=facility)
                return Response({
                    "code": status.HTTP_200_OK,
                    "message": "登录成功！",
                    "token":token,
                    'refresh_token':refresh_token,
                    "uid": user.id
                })
            else:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "密码错误！"
                })
        except Exception as e:
            print('错误>>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 忘记密码
class ForgetPwd(APIView):
    redis_conn = redis.Redis(host='localhost', port=6379, password='123', db=3)
    def put(self,request):
        try:
            name = request.data.get("name")
            password = request.data.get("password")
            pwd = request.data.get("pwd")
            mobile = request.data.get("mobile")
            sms_code = request.data.get("sms_code")

            user = UserModel.objects.filter(username=name, is_delete=False).first()
            if not user:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "没有找到该用户！"
                })
            if pwd != password:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "密码不一致！"
                })
            user_id = user.id

            if not UserDetailedModel.objects.filter(user_id=user_id,mobile=mobile,is_delete=False):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "用户手机号不正确！"
                })

            code_key = "sms_" + mobile
            # 验证验证码
            sms = self.redis_conn.get(code_key)
            if not sms:
                return Response({
                    'code': 204,
                    'msg': "验证码过期"
                })
            if sms.decode() != sms_code:
                return Response({
                    "code": 204,
                    'msg': "验证码错误"
                })
            hash_pwd = generate_password_hash(password)
            UserModel.objects.filter(id=user_id).update(password=hash_pwd)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改密码成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 用户
class UserView(ModelViewSet):
    queryset = UserModel.objects.filter(is_delete=False).all()
    serializer_class = UserSer

    # 添加用户信息
    def create(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            if username == None:
                return Response({"code": status.HTTP_204_NO_CONTENT,"message": "账号不能为空！"})
            if password == None:
                return Response({"code": status.HTTP_204_NO_CONTENT,"message": "密码不能为空！"})
            pwd = generate_password_hash(password)
            if UserModel.objects.filter(username=username):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "账号已存在！"
                })
            UserModel.objects.create(username=username, password=pwd, position_id=4)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "添加成功!"
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 学校
class SchoolAPIView(ModelViewSet):
    queryset = SchoolModel.objects.filter(is_delete=False).all()
    serializer_class = SchoolSer

    # 获取机构
    @check_login
    def list(self, request, *args, **kwargs):
        user_id = request.user
        print('user_id', user_id)
        if not UserModel.objects.filter(id=user_id, is_delete=False, position_id=1):
            return Response({
                "code": status.HTTP_204_NO_CONTENT,
                "message": "职位不符合要求！"
            })
        school = SchoolModel.objects.filter(is_delete=False).all()
        school_ser = SchoolSer(school, many=True).data
        school_list = json.loads(json.dumps(school_ser))
        print('school_ser', school_list)
        for i in school_list:
            user = UserDetailedModel.objects.filter(user_id=i['user_id']).first()
            print("================",user)
            i['user_name']=user.account
        return Response({
            "code": status.HTTP_200_OK,
            "message": "获取机构成功！",
            "data": school_list
        })

    # 添加学校
    @check_login
    def create(self, request, *args, **kwargs):
        try:
            user = request.user
            name = request.data.get("name")
            desc = request.data.get("desc")
            user_id = request.data.get("user_id")

            if not UserModel.objects.filter(id=user, is_delete=False, position_id=1):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求！"})
            if name == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "名字不能为空！"})
            if user_id == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "负责人不能为空！"})
            school = SchoolModel.objects.create(name=name, desc=desc, user_id=user_id)
            school_id = school.id
            UserModel.objects.filter(id=user_id).update(position_id=2, school_id=school_id)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "创建学校成功!"
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 修改学校
class SchoolOper(APIView):
    @check_login
    def put(self,request,pk):
        try:
            user_id = request.user
            user_name = UserModel.objects.filter(id=user_id, school_id=pk, is_delete=False, position_id=1).first()
            name = request.data.get('name')
            desc = request.data.get('desc')
            user = request.data.get("user")

            if not user_name:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "该用户不符合要求！"})
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "身份不符合要求！"})
            SchoolModel.objects.filter(id=pk).update(name=name,desc=desc,user_id=user)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改学校成功！"
            })
        except Exception as e:
            print('错误>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 删除学校
class DropSchool(APIView):
    @check_login
    def delete(self,request,pk):
        try:
            user_id = request.user
            user = UserModel.objects.filter(id=user_id, is_delete=False, school_id=pk, position_id=1).first()
            if not user:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "用户没有权限！"
                })
            grade = GradeMode.objects.filter(school_id=pk,is_delete=False).first()
            if grade:
                return Response({
                    "code": status.HTTP_200_OK,
                    "message": "请先删除该学校中的班级！"
                })
            SchoolModel.objects.filter(id=pk,is_delete=False).update(is_delete=True)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "删除学校成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 班级
class GradeSet(ModelViewSet):
    queryset = GradeMode.objects.filter(is_delete=False).all()
    serializer_class = GradeSer

    # 获取学校中的班级
    def list(self, request, *args, **kwargs):
        try:
            school_id = request.data.get('school_id')
            grade = GradeMode.objects.filter(school_id=school_id, is_delete=False).all()
            print("数据",grade.query)
            grade_ser = GradeSer(grade, many=True).data
            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取学校中的班级成功！",
                "data": grade_ser
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 添加班级
    @check_login
    def create(self, request, *args, **kwargs):
        try:
            user_name = request.user
            print('user_n ame', user_name)
            name = request.data.get('name')
            desc = request.data.get('desc')
            user_id = request.data.get('user_id')
            school = SchoolModel.objects.filter(user_id=user_name, is_delete=False).first()
            if not school:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "此用户不是学校负责人！"
                })
            school_id = school.id
            print('sho_id', school_id)

            user = UserModel.objects.filter(id=user_id, school_id=school_id, position_id=2, is_delete=False)
            print('iuse', user)
            if not user:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "用户不符合要求！"})
            if name == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "班级名不能为空!"})
            if user_id == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "负责人不能为空!"})

            if GradeMode.objects.filter(name=name, school_id=school_id, is_delete=False):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "该学校中已存在该班级！"
                })
            if UserModel.objects.filter(id=user_id, position_id=3, is_delete=False):
                grade = GradeMode.objects.create(name=name, desc=desc, school_id=school_id)
                print('grade', grade.id)
                TeacherGradeModel.objects.create(grade_id=grade.id, user_id=user_id)
                return Response({
                    "code": status.HTTP_200_OK,
                    "message": "添加班级成功!"
                })
            if UserModel.objects.filter(id=user_id, position_id=4, is_delete=False):
                grade = GradeMode.objects.create(name=name, desc=desc, school_id=school_id)
                print('grade', grade.id)
                UserModel.objects.filter(id=user_id).update(position_id=3)
                TeacherGradeModel.objects.create(grade_id=grade.id, user_id=user_id)
                return Response({
                    "code": status.HTTP_200_OK,
                    "message": "添加班级成功!"
                })
            if UserModel.objects.filter(id=user_id, position_id=None, is_delete=False):
                grade = GradeMode.objects.create(name=name, desc=desc, school_id=school_id)
                print('grade', grade.id)
                UserModel.objects.filter(id=user_id).update(position_id=3)
                TeacherGradeModel.objects.create(grade_id=grade.id, user_id=user_id)
                return Response({
                    "code": status.HTTP_200_OK,
                    "message": "添加班级成功!"
                })
            else:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "该用户已有其他职位！"
                })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 修改班级
class GradeOper(APIView):
    @check_login
    def put(self,request,pk):
        try:
            user_id = request.user
            print('user_id', user_id)
            name = request.data.get("name")
            desc = request.data.get("desc")
            teacher_id = request.data.get("teacher_id")

            user = UserModel.objects.filter(id=user_id, position_id=2, is_delete=False).first()
            print('user______',user)
            if not user:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "用户不符合要求！"
                })
            if UserModel.objects.filter(id=teacher_id,is_delete=False, position_id=1):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "该用户职位不符合要求！"
                })
            if UserModel.objects.filter(id=teacher_id,is_delete=False, position_id=2):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "该用户职位不符合要求！"
                })
            if UserModel.objects.filter(id=teacher_id,is_delete=False, position_id=None):
                UserModel.objects.filter(id=teacher_id).update(position_id=3)
            if UserModel.objects.filter(id=teacher_id,is_delete=False, position_id=4):
                UserModel.objects.filter(id=teacher_id).update(position_id=3)

            GradeMode.objects.filter(id=pk,is_delete=False).update(name=name,desc=desc)
            teacher = TeacherGradeModel.objects.filter(grade_id=pk,is_delete=False).first()
            TeacherGradeModel.objects.filter(grade_id=pk, is_delete=False).update(user_id=teacher_id)
            print('teac', teacher)
            teacher_user_id = teacher.user_id
            print("tec_user_id",teacher_user_id)
            if not TeacherGradeModel.objects.filter(user_id=teacher_user_id,is_delete=False):
                UserModel.objects.filter(id=teacher_user_id, is_delete=False).update(position_id=None)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改班级成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 删除班级
class DropGradeAPIView(APIView):
    @check_login
    def delete(self,request,pk):
        try:
            user_id = request.user
            if not UserModel.objects.filter(id=user_id,is_delete=False, position_id=2):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "职位不符合要求！"
                })
            if UserModel.objects.filter(grade_id=pk,is_delete=False):
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "请先删除该班级内的学生"
                })
            teacher = TeacherGradeModel.objects.filter(grade_id=pk,is_delete=False).first()
            user = teacher.user_id
            UserModel.objects.filter(id=user,is_delete=False).update(position_id=None)
            TeacherGradeModel.objects.filter(grade_id=pk).update(is_delete=True)
            GradeMode.objects.filter(id=pk,is_delete=False).update(is_delete=True)
            return Response({
                'code': status.HTTP_200_OK,
                "message": "删除成功！"
            })
        except Exception as e:
            print("错误》》", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 学生
class StudentSet(ModelViewSet):
    queryset = UserModel.objects.all()
    serializer_class = UserSer

    # 获取班级学生
    def list(self, request, *args, **kwargs):
        try:
            grade_id = request.data.get("grade_id")
            if grade_id == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "没有获取到班级信息！"})

            user_list = UserModel.objects.filter(grade_id=grade_id, is_delete=False).all()
            if not user_list:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "该班级没有学生，快去添加吧！"
                })
            user_ser = UserSer(user_list,many=True).data
            user_ser = json.loads(json.dumps(user_ser))
            for i in user_ser:
                user_data = UserDetailedModel.objects.filter(user_id=i['id']).all()
                user_data_ser = UserDetailedSer(user_data,many=True).data
                i['user_data'] = user_data_ser
            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取成功！",
                "stu_list": user_ser
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

    # 添加学生
    @check_login
    def create(self, request, *args, **kwargs):
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            grade_id = request.data.get("grade_id")
            account = request.data.get('account')
            user = request.user
            if not UserModel.objects.filter(id=user,is_delete=False, position_id=3):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "职位不符合要求！"})

            if username == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "账号不能为空!"})
            if password == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "密码不能为空!"})
            if grade_id == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "班级不能为空!"})
            if account == None:
                return Response({"code": status.HTTP_204_NO_CONTENT, "message": "姓名不能为空!"})

            grade = GradeMode.objects.filter(id=grade_id, is_delete=False).first()
            school_id = grade.school_id

            pwd = generate_password_hash(password)
            user = UserModel.objects.create(username=username, password=pwd,grade_id=grade_id, position_id=4, school_id=school_id)
            user_id = user.id
            print('user_id', user_id)
            UserDetailedModel.objects.create(user_id=user_id, account=account)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "添加学生成功！"
            })
        except Exception as e:
            print("错误", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": "服务器错误"
            })


# 修改学生
class AmendStudent(APIView):
    @check_login
    def put(self, request,pk):
        try:
            user_id = request.user
            account = request.data.get("account")
            mobile = request.data.get("mobile")
            age = request.data.get("age")
            sex = request.data.get("sex")
            avatar_url = request.data.get("avatar_url")
            email = request.data.get("email")

            if not UserModel.objects.filter(id=user_id, position_id=3, is_delete=False):
                return Response({"code": status.HTTP_204_NO_CONTENT, 'message': '职位不符合！'})
            if not UserDetailedModel.objects.filter(user_id=pk,is_delete=False):
                return Response({"code": status.HTTP_204_NO_CONTENT, "message":"用户不存在！"})
            UserDetailedModel.objects.filter(user_id=pk).update(account=account,mobile=mobile,age=age,
                                                                sex=sex,avatar_url=avatar_url,email=email)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改学生信息成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 删除学生
class DroStudent(APIView):
    @check_login
    def delete(self, request,pk):
        try:
            user_id = request.user
            if not UserModel.objects.filter(id=user_id, position_id=3, is_delete=False):
                return Response({"code": status.HTTP_204_NO_CONTENT, 'message': '职位不符合！'})

            if not UserDetailedModel.objects.filter(user_id=pk, is_delete=False):
                return Response({'code': status.HTTP_204_NO_CONTENT, "message": "用户不存在！"})

            UserModel.objects.filter(id=pk,is_delete=False).update(is_delete=True)
            UserDetailedModel.objects.filter(user_id=pk).update(is_delete=True)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "删除学生成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 获取登录的用户
class LoginRoleAPIView(APIView):
    @check_login
    def get(self,request):
        try:
            user = request.user
            user_list = UserModel.objects.filter(id=user, is_delete=False).first()
            user_ser = UserSer(user_list).data
            user_ser_list = json.loads(json.dumps(user_ser))
            user_data = UserDetailedModel.objects.filter(is_delete=False,user_id=user_ser_list["id"]).first()
            user_ser['account'] = user_data.account
            user_ser['mobile'] = user_data.mobile
            user_ser['age'] = user_data.age
            user_ser['sex'] = user_data.sex
            user_ser['avatar_url'] = user_data.avatar_url
            user_ser['email'] = user_data.email
            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取用户信息成功！",
                "data": user_ser
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 获取班级的老师
class GradeTeacherAPIView(APIView):
    def get(self,request):
        try:
            grade_id = request.data.get("grade_id")
            print('grade', grade_id)
            grade_teacher = TeacherGradeModel.objects.filter(grade_id=grade_id, is_delete=False).all()
            print(grade_teacher)
            grade_teacher_ser = TeacherGradeSer(grade_teacher, many=True).data
            grade_teacher_list = json.loads(json.dumps(grade_teacher_ser))
            grade_teacher_data = []
            for i in grade_teacher_list:
                user = UserModel.objects.filter(id=i['user_id'],is_delete=False).all()
                user_ser = UserSer(user,many=True).data
                user_list = json.loads(json.dumps(user_ser))
                grade_teacher_data.append(user_list)

                for j in user_list:
                    user_data = UserDetailedModel.objects.filter(user_id=j['id'],is_delete=False).all()
                    user_data_ser = UserDetailedSer(user_data,many=True).data
                    j['user_data'] = user_data_ser

            return Response({
                "code": status.HTTP_200_OK,
                "message": "获取班级的教师成功",
                "data": grade_teacher_data
            })
        except Exception as e:
            print("错误>>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 获取时间段的问候语
class GreetingsAPIView(APIView):
    # 获取问候语
    def get(self, request):
        try:
            timing = datetime.datetime.now().hour
            greeting = GreetingsModel.objects.filter(Q(start_time__lte=timing) & Q(end_time__gte=timing)).all()
            greeting = GreetingSer(greeting, many=True)
            greeting = json.loads(json.dumps(greeting.data))
            dan = random.choice(greeting)
            return Response({
                'code': status.HTTP_200_OK,
                'msg': '获取成功',
                'data': dan
            })
        except Exception as e:
            return Response({
                'code': status.HTTP_500_INTERNAL_SERVER_ERROR,
                'msg': f'服务器错误{e}'
            })


# 修改密码
class ChangePwd(APIView):
    def put(self,request,pk):
        try:
            password = request.data.get("password")
            passwords = request.data.get("passwords")

            if not password == passwords:
                return Response({
                    "code": status.HTTP_204_NO_CONTENT,
                    "message": "两次密码不一致！"
                })

            pwd = generate_password_hash(passwords)
            UserModel.objects.filter(id=pk,is_delete=False).update(password=pwd)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改用户密码成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })


# 修改个人信息
class UpdUserInfo(APIView):
    @check_login
    def put(self,request):
        try:
            user_id = request.user
            account= request.data.get('account')
            age= request.data.get('age')
            sex= request.data.get('sex')
            avatar_url= request.data.get('avatar_url')
            email= request.data.get('email')
            mobile= request.data.get('mobile')
            UserDetailedModel.objects.filter(user_id=user_id, is_delete=False).update(account=account,age=age,sex=sex,
                                                                     avatar_url=avatar_url,email=email,mobile=mobile)
            return Response({
                "code": status.HTTP_200_OK,
                "message": "修改个人信息成功！"
            })
        except Exception as e:
            print('错误>>>', e)
            return Response({
                "code": status.HTTP_500_INTERNAL_SERVER_ERROR,
                "message": f"服务器错误{e}"
            })

